<template>
  <div class="pageheader">
    <el-page-header @back="toProjectView">
      <template #content>
        <span> {{ info.project.name }} </span>
      </template>
    </el-page-header>
  </div>
  <div style="margin: 20px">
    <el-card>
      <div style="margin-bottom: 10px; display: flex">
        <el-input class="w-50 m-2" style="width: 150px" placeholder="请输入关键词" v-model="form.keywords"/>
        <el-button style="margin-left: 10px" type="primary" @click="getSolutionList">关键词搜索</el-button>
        <el-button @click="openAddSolutionDialogue">新建方案</el-button>
        <el-button @click="compareSolutions">方案比选</el-button>
      </div>
      <el-table ref="viewTable" :data="state.tableData" :border="true" highlight-current-row class="dataTable"
                @selection-change="selectionChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="id" label="ID" width="50" fixed="left"/>
        <el-table-column prop="name" label="方案标题" width="150"/>
        <el-table-column prop="description" label="方案描述"/>
        <el-table-column prop="createTime" label="建立时间" width="150"/>
        <el-table-column label="操作" width="350" fixed="right">
          <template v-slot="scope">
            <el-button link size="small" @click="openEditSolutionDialogue(scope.row)">编辑</el-button>
            <el-button link type="primary" size="small" @click="toIndicatorEditView(scope.row)">方案设计</el-button>
            <el-button link type="primary" size="small" @click="evaluate(scope.row)">评价</el-button>
            <el-button link type="primary" size="small" @click="toEvaluationResultView(scope.row)">查看评价</el-button>
            <el-popconfirm title="是否确认删除该项？" confirm-button-text="是" cancel-button-text="否"
                           @confirm="deleteSolution(scope.row.id)">
              <template #reference>
                <el-button link type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>

            <el-dropdown>
                  <span style="font-size: 12px; margin-top: 7px; margin-left: 12px">
                    更多操作
                  </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-button link size="small" @click="copySolution(scope.row.id)">复制方案</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button link size="small" @click="downloadTemplate(scope.row.id)">下载模板</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button link size="small" @click="this.dlgImportState.visible = true; this.dlgImportState.form.id=scope.row.id">导入指标</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button link size="small" @click="downloadIndicatorExcel(scope.row.id)">导出指标</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button link size="small" @click="downloadReport(scope.row.id)">导出报告</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="pagination" v-model:current-page="form.current" v-model:page-size="form.size"
                     :page-sizes="[10, 20, 50]" :small="false" :disabled="false" :background="true"
                     layout="total, sizes, prev, pager, next, jumper" :total="state.total"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"/>
    </el-card>
  </div>
  <!-- 新增方案 -->
  <el-dialog v-model="dlgState.visible" :title="dlgState.title" :width="600" @close="clean">
    <el-form :model="dlgState.form" ref="dlg_form">
      <el-form-item label="方案名称：" prop="name">
        <el-input v-model="dlgState.form.name"></el-input>
      </el-form-item>
      <el-form-item label="方案描述：" prop="description">
        <el-input v-model="dlgState.form.description" type="textarea" :rows="3"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialogue">返回</el-button>
        <el-button type="primary" @click="addSolution" v-if="dlgState.isAdd">
          新增
        </el-button>
        <el-button type="primary" @click="editSolution" v-else> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 导入指标 -->
  <el-dialog v-model="dlgImportState.visible" title="导入指标" :width="600" @close="clean">
    <el-form :model="dlgImportState.form" ref="dlg_form">
      <el-form-item  label="文件" prop="file" required>
        <el-upload action="#" :auto-upload="false" :multiple="false" :file-list="fileList" :limit="1"
                   :on-change="changePic" :on-remove="removePic">
          <el-button type="primary">选择文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="this.dlgImportState.visible = false">返回</el-button>
        <el-button type="primary" @click="importIndicator">
          上传
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
import {ref, reactive} from "vue";
import {ElMessage} from "element-plus";
import solutionApi from "@/api/evaluation/solution";
import indicatorApi from "@/api/evaluation/indicator"
import router from "@/router";
import {request} from "@/api/REQ";

export default {
  props: {
    projectType: {default: 1, type: Number}
  },
  data() {
    return {
      urlPrefix: "",
      project: {
        id: 0
      },
      info: {
        project: {
          id: 0,
          name: "",
          projectType: 1,
          description: "",
          createTime: ""
        },
      },
      form: reactive({
        current: 1,
        keywords: "",
        size: 10,
      }),
      state: reactive({
        total: 0,
        tableData: [],
      }),
      dlg_form: ref(),
      dlgState: reactive({
        visible: false,
        isAdd: true,
        title: "新增方案",
        form: {
          id: 0,
          name: "",
          description: "",
          projectId: 0,
        },
      }),
      dlgImportState : reactive({
        visible: false,
        form : {
          id :0,
          file : null
        }
      }),
      multipleSelection: ref()
    }
  },
  methods: {
    /**
     * 方案操作
     */
    getSolutionList() {
      solutionApi.get(this.info.project.id, this.form).then((res) => {
        if (res.status === 200) {
          if (res.data.code === 200) {
            this.state.tableData = res.data.data.records;
            this.state.total = res.data.data.total;
          } else {
            ElMessage.error("获取列表失败")
          }
        } else {
          ElMessage.error("获取列表失败")
        }
      });
    },
    addSolution() {
      this.dlgState.form.projectId = this.info.project.id;
      solutionApi.add(this.dlgState.form).then((res) => {
        if (res.status === 200) {
          if (res.data.code === 500) {
            ElMessage.error(res.data.message);
          } else {
            ElMessage.success("添加成功");
            this.dlgState.visible = false;
            this.getSolutionList();
          }
        } else {
          ElMessage.error("操作失败")
        }
      });
    },
    editSolution() {
      solutionApi.update(this.dlgState.form).then((res) => {
        console.log(res);
        if (res.status === 200) {
          if (res.data.code === 500) {
            ElMessage.error(res.data.message);
          } else {
            ElMessage.success("操作成功");
            this.dlgState.visible = false;
            this.getSolutionList();
          }
        }
      });
    },
    // 删除方案
    deleteSolution(solId) {
      solutionApi.del(solId).then((res) => {
        if (res.status === 200) {
          if (res.data.code === 500) {
            ElMessage.error(res.data.message);
          } else {
            ElMessage.success("操作成功");
            this.dlgState.visible = false;
            this.getSolutionList();
          }
        } else {
          ElMessage.error("操作失败");
        }
      });
    },
    evaluate(row) {
      solutionApi.eva(row.id, this.projectType).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success("评价完成");
        } else {
          ElMessage.error("评价失败");
        }
      });
    },
    importIndicator(){
      console.log(this.dlgImportState.form.file)
      indicatorApi.importIndicator(this.dlgImportState.form.id, {file : this.dlgImportState.form.file}).then((res) => {
        console.log(res)
        ElMessage.success("解析成功")
      })
    },
    downloadIndicatorExcel(id) {
      window.open(`http://localhost:8001/indicator/output/${id}&ALL&${this.projectType}`);
    },
    downloadReport(id) {
      if (this.projectType == 2){
        window.open(`http://localhost:8001/solution/report/${id}/${this.projectType}`);
      }else {
        ElMessage.error("该模块暂未开通此功能。")
      }
    },
    downloadTemplate(id){
      window.open(`http://localhost:8001/indicator/template/${id}`);
    },
    copySolution(id) {
      solutionApi.copy(id).then((res) => {
        if (res.status === 200) {
          if (res.data.code === 500) {
            ElMessage.error(res.data.message)
          } else {
            ElMessage.success("复制成功")
            this.getSolutionList()
          }
        } else {
          ElMessage.error("操作失败")
        }
      })
    },
    compareSolutions() {
      let form = [];
      if (this.multipleSelection === undefined){
        ElMessage.warning("尚未选择方案");
        return;
      }
      for (const item of this.multipleSelection) {
        form.push(item);
      }
      if (form.length === 0) {
        ElMessage.warning("尚未选择方案");
        return;
      }
      window.sessionStorage.setItem(this.urlPrefix + "Compare", JSON.stringify(form))
      router.push("/" + this.urlPrefix + "/compare")
    },

    /**
     * 页面操作
     */
    selectionChange(val) {
      this.multipleSelection = val;
    },
    openAddSolutionDialogue() {
      this.dlgState.title = "新增方案";
      this.dlgState.isAdd = true;
      this.dlgState.visible = true;
    },
    //编辑方案基本信息
    openEditSolutionDialogue(row) {
      this.dlgState.form = row;
      this.dlgState.title = "编辑方案";
      this.dlgState.isAdd = false;
      this.dlgState.visible = true;
    },
    closeDialogue() {
      this.dlgState.visible = false;
    },
    clean() {
      this.dlgState.form = {
        id: 0,
        name: "",
        description: "",
        projectId: this.info.project.id,
      };
    },
    toProjectView() {
      router.push("/" + this.urlPrefix);
    },
    toIndicatorEditView(row) {
      window.sessionStorage.setItem(this.urlPrefix + "Solution", JSON.stringify(row));
      router.push("/" + this.urlPrefix + "/solution/indicator");
    },
    // 评价
    toEvaluationResultView(row) {
      window.sessionStorage.setItem(this.urlPrefix + "Solution", JSON.stringify(row));
      router.push("/" + this.urlPrefix + "/solution/eva");
    },
    changePic(file){
      this.dlgImportState.form.file = file.raw;
    },
//删除文件
    removePic(){
      this.dlgImportState.form.file = null;
    },
    // 调整分页大小
    handleSizeChange(val) {
      this.form.size = val;
      this.getSolutionList();
    },
    // 跳转页面
    handleCurrentChange(val) {
      this.form.current = val;
      this.getSolutionList();
    },
  },
  mounted() {
    if (this.projectType == 1) {
      this.urlPrefix = "generic"
    } else if (this.projectType == 2) {
      this.urlPrefix = "infrastructure"
    } else if (this.projectType == 3) {
      this.urlPrefix = "purchase"
    } else if (this.projectType == 4) {
      this.urlPrefix = "repair"
    } else if (this.projectType == 5) {
      this.urlPrefix = "update"
    }
    // 初始化项目基本信息
    this.project = window.sessionStorage.getItem(this.urlPrefix + "Project");
    if (this.project !== null) {
      this.info.project = JSON.parse(this.project);
    } else {
      ElMessage.error("未获取到项目信息！");
    }
    this.getSolutionList()
  }
}

// type definition
// type project = {
//   id: number;
//   name: string;
//   type: number;
//   createTime: Date;
//   description: string;
// };

</script>
<style lang="scss" scoped>
.tabs > .el-tabs__content {
  width: 100%;
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.tabs {
  margin: 20px;
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>
